package com.ruoyi.web.controller.api;

import cn.dev33.satoken.annotation.SaIgnore;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.Md5Util;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.SysLoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app")
public class AppLoginController {
    private final SysLoginService loginService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/login")
    public R<Map<String, Object>> login(@Validated @RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();

        // 解密
        String stringJson = new String(Base64.getDecoder().decode(loginBody.getData()));
        JSONObject jsonObject = JSON.parseObject(stringJson);
        if (StringUtils.isBlank(jsonObject.getString("username"))) {
            throw new RuntimeException("用户名不能为空");
        }
        if (StringUtils.isBlank(jsonObject.getString("password"))) {
            throw new RuntimeException("密码不能为空");
        }
        loginBody.setUsername(jsonObject.getString("username"));
        loginBody.setPassword(jsonObject.getString("password"));
        //
        // 生成令牌
        String token = loginService.loginForApp(loginBody.getUsername(), Md5Util.encrypt3ToMD5(loginBody.getPassword()));
        ajax.put(Constants.TOKEN, token);
        return R.ok(ajax);
    }

}
